<template>
  <div>
    <el-row :gutter="10" class="containerView">
      <!--table-->
      <el-col :span="24" :xs="24" class="mainHeight">
        <el-card shadow="always" class="mainHeight">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="班级" prop="school_class_id">
              <el-select
                v-model="queryParams.school_class_id"
                placeholder="请选择班级"
                clearable
                style="width: 200px"
                @change="getOrdersListHandle"
              >
                <el-option
                  v-for="item in schoolClassesList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="日期" prop="start_date">
              <el-date-picker
                v-model="queryParams.start_date"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 200px"
                @change="getOrdersListHandle"
              />
            </el-form-item>

            <el-form-item style="float: right">
              <el-button
                @click="reset"
                plain
                icon="el-icon-refresh"
                size="small"
                >刷新</el-button
              >
              <!-- <el-button
                @click="addOrderHandle"
                type="primary"
                size="small"
                icon="el-icon-plus"
                >添加</el-button
              > -->
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            :data="tableList"
            height="70vh"
            style="width: 100%"
            default-expand-all
          >
            <!-- <el-table-column
              label="订单id"
              prop="id"
              :show-overflow-tooltip="true"
            >
            </el-table-column> -->
            <el-table-column
              label="设备id"
              prop="serial_number"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="时间"
              prop="date"
              :show-overflow-tooltip="true"
            >

            </el-table-column>
            <el-table-column
              label="模式使用时间"
              prop="items"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <div v-for="item in scope.row.items">
                  {{ item.device_mode }}:{{ item.duration_seconds }}秒
                </div>
              </template>
            </el-table-column>
             <el-table-column
              label="用户信息"
              prop="user"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <div>
                  昵称：{{ scope.row.user.nickname }}
                </div>
                <div>
                  学校：{{ scope.row.user.school?scope.row.user.school.name:'未绑定'  }}
                </div>
                <div>
                  年纪：{{ scope.row.user.school_grade?scope.row.user.school_grade.name: '未绑定' }}
                </div>
                <div>
                  班级：{{ scope.row.user.school_class?scope.row.user.school_class.name: '未绑定' }}
                </div>
                <div>
                  学号：{{ scope.row.user.student_id|| '未绑定' }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              label="创建时间"
              prop="created_at"
              :show-overflow-tooltip="true"
            >

            </el-table-column>



            <!-- <el-table-column
              width="200"
              label="操作"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="editOrderHandle(scope.row.id)"
                  >编辑</el-button
                >


                <el-button
                  class="text-danger"
                  type="text"
                  size="mini"
                  @click="deleteHandle(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column> -->
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.page_size"
            @pagination="getOrdersListHandle"
          />
        </el-card>


      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  ordersList,
  addOrders,
  editOrders,
  delOrders,
  orderProgressList,
  orderStatusesList,
} from "@/api/order";

import { customersList, customerSourcesList } from "@/api/custmoer";
import { suppliersList } from "@/api/suppliers";
import { getPaymentPeriodsList } from "@/api/system/paymentPeriods";
import { listUser } from "@/api/system/user";

import { getToken } from "@/utils/auth";
export default {
  name: "Customer",
  data() {
    return {
      filterText: "",
      // 遮罩层
      loading: false,
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 15,
        start_date: "",
        end_date: "",
        school_class_id: "",
      },

      tableList: [],
      senceList: [],
      areaList: [],
      editShow: false,
      formData: {
        id: "",
        customer_id: "",
        supplier_id: "",
        order_status_id: "",
        order_process_id: "",
        customer_payment_period_id: "",
        accept_at: "",
        customs_broker: "",
        delivery_party: "",
        customer_billing_weight: "",
        supplier_billing_weight: "",
        shipper: "",
        receiver: "",
        notify_person: "",
        file: "",
        bl_file: "",
        remark: "",
        mark: "",
        customer_air_freight_price: "",
        supplier_air_freight_price: "",
      },

      formRules: {
        customer_category_id: [
          { required: true, trigger: "blur", message: "请选择客户分类" },
        ],
        customer_source_id: [
          { required: true, trigger: "blur", message: "请选择客户来源" },
        ],
        customer_status_id: [
          { required: true, trigger: "blur", message: "请选择客户状态" },
        ],

        name: [{ required: true, trigger: "blur", message: "请输入客户名称" }],
        fixed_limit: [
          { required: true, trigger: "blur", message: "请输入客户固定额度" },
        ],
        temp_limit: [
          { required: true, trigger: "blur", message: "请输入客户名临时额度" },
        ],
      },
      dialogVisible: false,
      updateShow: false,

      newAreaList: [],
      ruleLoading: false,
      actionUrl: "",
      header: {
        Authorization: "Bearer " + getToken(),
      },
      statusList: [],
      sourceList: [],
      categoriesList: [],
      contactsList: [],

      editSubjectShow: false,
      subjectsAddDialogVisible: false,
      customersList: [],
      suppliersList: [],
      paymentPeriodsList: [],
      notifyPersonList: [],
      receiverList: [],
      shiperList: [],
      schoolClassesList: [],
    };
  },
  watch: {},
  created() {
    this.getOrdersListHandle();
    // this.orderProgressListHandle();
    // this.orderStatusesListHandle();
    // this.getCustomersListHandle();
    // this.getSuppliersListHandle();
    // this.getPaymentPeriodsListHandle();
    // this.getUserListHandle();
    this.getSchoolClassesListHandle();
  },
  methods: {
    getUserListHandle() {
      listUser().then((res) => {
        this.notifyPersonList = res.data;
        this.receiverList = res.data;
        this.shipperList = res.data;
      });
    },
    getPaymentPeriodsListHandle() {
      getPaymentPeriodsList().then((res) => {
        this.paymentPeriodsList = res.data;
      });
    },
    getCustomersListHandle() {
      customersList().then((res) => {
        this.customersList = res.data;
      });
    },
    getSuppliersListHandle() {
      suppliersList().then((res) => {
        this.suppliersList = res.data;
      });
    },

    // 获取班级列表
    getSchoolClassesListHandle() {
      customerSourcesList({
        is_paginate: 0,
      }).then((res) => {
        this.schoolClassesList = res.data;
      });
    },
    //删除开票资料
    delSubjectsHandle(row) {
      this.$modal.confirm("是否确认删除此条数据？").then(() => {
        delInvoiceSubjects({ id: row.id }).then((res) => {
          this.$message.success("删除成功");
          this.getInvoiceSubjectsHandle();
        });
      });
    },
    delContactsHandle(row) {
      this.$modal.confirm("是否确认删除此条数据？").then(() => {
        delContacts({ id: row.id }).then((res) => {
          this.$message.success("删除成功");
          this.getContactsListHandle();
        });
      });
    },
    //编辑开票资料
    addSubjectsHandle(row) {
      this.$refs.addsubjectForm.validate((valid) => {
        if (valid) {
          if (this.editSubjectShow) {
            editInvoiceSubjects(this.invoiceSubjectsFormData).then((res) => {
              this.$message.success("编辑成功");
              this.subjectsAddDialogVisible = false;
              this.getInvoiceSubjectsHandle();
            });
          } else {
            addInvoiceSubjects(this.invoiceSubjectsFormData).then((res) => {
              this.$message.success("添加成功");
              this.subjectsAddDialogVisible = false;
              this.getInvoiceSubjectsHandle();
            });
          }
        }
      });
    },

    // 编辑联系人
    addContactsHandle() {
      this.$refs.addContactForm.validate((valid) => {
        console.log(this.contactsFormData);
        if (valid) {
          if (this.editContactShow) {
            editContacts(this.contactsFormData).then((res) => {
              this.$message.success("编辑成功");
              this.contactsAddDialogVisible = false;
              this.getContactsListHandle();
            });
          } else {
            addContacts(this.contactsFormData).then((res) => {
              this.$message.success("添加成功");
              this.contactsAddDialogVisible = false;
              this.getContactsListHandle();
            });
          }
        }
      });
    },
    // 编辑开票资料
    editSubjectsHandle(row) {
      this.subjectsAddDialogVisible = true;
      this.invoiceSubjectsFormData.customer_id =
        this.invoiceSubjectsFormData.customer_id;
      this.invoiceSubjectsFormData.id = row.id;
      this.invoiceSubjectsFormData.header = row.header;
      this.invoiceSubjectsFormData.tax_number = row.tax_number;
      this.invoiceSubjectsFormData.bank_name = row.bank_name;
      this.invoiceSubjectsFormData.bank_account = row.bank_account;
      this.invoiceSubjectsFormData.phone = row.phone;
      this.invoiceSubjectsFormData.address = row.address;
      this.editSubjectShow = true;
    },
    // 编辑联系人
    editContactsHandle(row) {
      this.contactsAddDialogVisible = true;
      this.contactsFormData.customer_id = this.contactsFormData.customer_id;
      this.contactsFormData.id = row.id;
      this.contactsFormData.name = row.name;
      this.contactsFormData.phone = row.phone;
      this.contactsFormData.address = row.address;
      this.editContactShow = true;
    },
    // 点击添加开票资料
    clickAddSubjects() {
      this.subjectsAddDialogVisible = true;
      this.invoiceSubjectsFormData = {
        id: "",
        customer_id: this.invoiceSubjectsFormData.customer_id,
        header: "",
        tax_number: "",
        bank_name: "",
        bank_account: "",
        phone: "",
        address: "",
      };
      this.editSubjectShow = false;
    },
    //点击添加联系人
    clickAddContacts() {
      this.contactsAddDialogVisible = true;
      this.contactsFormData = {
        id: "",
        customer_id: this.contactsFormData.customer_id,
        name: "",
        phone: "",
        address: "",
      };
      this.editContactShow = false;
    },
    clickCustomerIdHandle(row) {
      this.contactsFormData.customer_id = row.id;
      this.getContactsListHandle();
    },
    //点击开票资料
    clickSubjectsIdHandle(row) {
      this.invoiceSubjectsFormData.customer_id = row.id;
      this.getInvoiceSubjectsHandle();
    },
    //获取开票资料列表
    getInvoiceSubjectsHandle() {
      this.invoiceSubjectsDialogVisible = true;
      invoiceSubjects({
        customer_id: this.invoiceSubjectsFormData.customer_id,
      }).then((res) => {
        this.subjectsList = res.data;
      });
    },
    // 获取联系人列表
    getContactsListHandle() {
      getContactsList({
        customer_id: this.contactsFormData.customer_id,
      }).then((res) => {
        this.contactsList = res.data;
        this.contactsDialogVisible = true;
      });
    },
    orderProgressListHandle() {
      orderProgressList().then((res) => {
        this.progressList = res.data;
      });
    },
    orderStatusesListHandle() {
      orderStatusesList().then((res) => {
        this.statusList = res.data;
      });
    },

    addCardStylesHandle() {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          if (this.editShow) {
            editOrders(this.formData).then((res) => {
              this.$message.success("编辑成功");
              this.dialogVisible = false;
              this.getOrdersListHandle();
            });
          } else {
            addOrders(this.formData).then((res) => {
              this.$message.success("添加成功");
              this.dialogVisible = false;
              this.getOrdersListHandle();
            });
          }
        }
      });
    },
    handleAvatarSuccess(res, file) {
      let that = this;
      that.formData.image = res.path;
      that.Imgurl = res.url;
      that.$forceUpdate(); // 强制更新视图
    },
    beforeAvatarUpload(file) {},
    getOrdersListHandle() {
      this.loading = true;
      
      this.queryParams.end_date = this.queryParams.start_date;
      ordersList(this.queryParams)
        .then((res) => {
          this.tableList = res.data;
          this.total = res.meta.total;
          this.loading = false;
          // console.log(this.tableList);
        })
        .catch((error) => {
          this.loading = false;
        });
    },

    deleteHandle(row) {
      this.$modal
        .confirm("是否确认删除此条数据？")
        .then(async () => {
          const { code } = await delOrders({
            id: row.id,
          });
          this.$message.success("删除成功");
          this.getOrdersListHandle();
        })
        .then(() => {})
        .catch(() => {});
    },

    updateHandle(cell) {
      let data = JSON.parse(JSON.stringify(cell));
      this.formData.id = data.id;
      this.formData.customer_category_id = data.customer_category.id;
      this.formData.customer_source_id = data.customer_source.id;
      this.formData.customer_status_id = data.customer_status.id;
      this.formData.name = data.name;
      this.formData.temp_limit = Number(data.temp_limit);
      this.formData.fixed_limit = Number(data.fixed_limit);
      this.formData.remark = data.remark;
      this.editShow = true;
      this.dialogVisible = true;
    },
    addHandle() {
      this.editShow = false;
      this.dialogVisible = true;
      this.formData = {
        id: "",
        customer_id: "",
        supplier_id: "",
        order_status_id: "",
        order_process_id: "",
        customer_payment_period_id: "",
        accept_at: "",
        customs_broker: "",
        delivery_party: "",
        customer_billing_weight: "",
        supplier_billing_weight: "",
        shipper: "",
        receiver: "",
        notify_person: "",
        file: "",
        bl_file: "",
        remark: "",
        mark: "",
        customer_air_freight_price: "",
        supplier_air_freight_price: "",
      };
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      getCategories(6, {
        format: "tree",
      }).then((res) => {
        if (res.code == 0) {
          this.deptOptions = res.data.categories;
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (this.queryParams.paper_type == data.id) {
        this.queryParams.paper_type = undefined;
      } else {
        this.queryParams.paper_type = data.id;
      }

      this.handleQuery();
    },

    // 表单重置
    reset() {
      this.queryParams = {
        page: 1,
        page_size: 15,
        school_class_id: undefined,
        start_date: undefined,
        end_date: undefined,
      };
      this.filterText = undefined;
      this.getOrdersListHandle();
    },

    handleDelete() {
      const ids = this.ids;
      console.log(this.ids);
      this.$modal
        .confirm('是否确认删除编号ID为"' + ids + '"的数据项？')
        .then(async () => {
          const { code } = await delPaper({
            ids: this.ids,
          });
          console.log(1);
          if (code === 0) {
            this.$message.success("删除成功");
            this.handleQuery();
          }
          // return delUser(userIds);
        })
        .then(() => {
          console.log(2);
          // this.getList();
          // this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          console.log(3);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleImageError(event) {
      console.error("图片加载失败:", event.target.src);
      this.$message.error("图片加载失败，请检查图片地址或网络连接");
    },
    addOrderHandle() {
      this.$router.push({
        path: "/order/detail",
        query: {
          type: "add",
          title: "添加订单",
        },
      });
    },
    editOrderHandle(id) {
      this.$router.push({
        path: "/order/detail",
        query: {
          id,
          type: "edit",
          title: "编辑订单",
        },
      });
    }
  },
};
</script>
<style scoped scss>
@import url("~@/assets/styles/dialog_wangpx.scss");
.th {
  word-break: break-word;
  background-color: #f8f8f9;
  color: #515a6e;
  font-weight: 700;
  height: 40px;
  font-size: 13px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #dfe6ec;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: none;
}
</style>
